﻿using MultiDAQ_Analysis.Model;
using MultiDAQ_Analysis.Util;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using System.Reflection; // === 添加这个引用 ===

namespace MultiDAQ_Analysis.View
{
    public partial class UcCenterView : UserControl
    {
        private int channelCount = AppConfig.ChannelCount;
        private PlotViewPanel plotPanel;
        private UIButton[] channelHeaders;
        private int currentSelectedChannel = -1;
        private Timer headerSyncTimer; // 表头同步定时器

        // 新增：统计相关字段
        private HighPerformanceDataAdapter dataAdapter;
        private Timer statisticsUpdateTimer; // 统计数据更新定时器
        private List<ChannelData> channelDataList; // 通道配置数据
        private Dictionary<int, ThresholdData> channelThresholds; // 通道阈值缓存

        private Dictionary<int, string> lastAlphaValues = new Dictionary<int, string>();
        private Dictionary<int, string> lastBetaValues = new Dictionary<int, string>();
        private Dictionary<int, string> lastDeductValues = new Dictionary<int, string>();


        public UcCenterView()
        {
            InitializeComponent();
            // === 添加这几行，启用双缓冲减少闪烁 ===
            this.SetStyle(ControlStyles.AllPaintingInWmPaint |
                          ControlStyles.UserPaint |
                          ControlStyles.DoubleBuffer, true);
            tableLayoutPanel.GetType().InvokeMember("DoubleBuffered",
                BindingFlags.SetProperty | BindingFlags.Instance | BindingFlags.NonPublic,
                null, tableLayoutPanel, new object[] { true });

            BuildTableLayout();
            InitPlotPanel();
            InitHeaderSync();
            InitStatisticsSystem(); // 初始化统计系统
        }

        // 新增：初始化统计系统
        private void InitStatisticsSystem()
        {
            // 加载通道配置数据
            channelDataList = ChannelDataManager.LoadAllChannelData();
            channelThresholds = new Dictionary<int, ThresholdData>();

            // 缓存阈值数据
            for (int i = 0; i < channelDataList.Count && i < channelCount; i++)
            {
                channelThresholds[i] = channelDataList[i].Thresholds;
            }

            // 初始化统计更新定时器
            statisticsUpdateTimer = new Timer { Interval = 1000 }; // 每秒更新一次
            statisticsUpdateTimer.Tick += StatisticsUpdateTimer_Tick;

            Console.WriteLine("[UcCenterView] 统计系统已初始化");
        }

        // 新增：统计数据更新定时器事件
        private void StatisticsUpdateTimer_Tick(object sender, EventArgs e)
        {
            try
            {
                // 获取所有通道的最新统计数据
                var allStatistics = ChannelDataManager.GetAllChannelStatistics();

                // 暂停布局以提高性能
                //tableLayoutPanel.SuspendLayout();

                // 更新界面显示
                for (int i = 0; i < channelCount; i++)
                {
                    if (allStatistics.ContainsKey(i))
                    {
                        var stats = allStatistics[i];

                        // 格式化新值
                        string newAlphaValue = FormatCount(stats.TotalAlphaPoints);
                        string newBetaValue = FormatCount(stats.TotalBetaPoints);
                        string newDeductValue = FormatCount(stats.TotalDeductedPoints);

                        // 只在值发生变化时更新
                        bool needUpdate = false;

                        if (!lastAlphaValues.ContainsKey(i) || lastAlphaValues[i] != newAlphaValue)
                        {
                            lastAlphaValues[i] = newAlphaValue;
                            needUpdate = true;
                        }

                        if (!lastBetaValues.ContainsKey(i) || lastBetaValues[i] != newBetaValue)
                        {
                            lastBetaValues[i] = newBetaValue;
                            needUpdate = true;
                        }

                        if (!lastDeductValues.ContainsKey(i) || lastDeductValues[i] != newDeductValue)
                        {
                            lastDeductValues[i] = newDeductValue;
                            needUpdate = true;
                        }

                        // 只有在值发生变化时才更新UI
                        if (needUpdate)
                        {
                            UpdateChannelData(i, newAlphaValue, newBetaValue, newDeductValue);
                        }
                    }
                }

                // 恢复布局
                tableLayoutPanel.ResumeLayout(false);
            }
            catch (Exception ex)
            {
                tableLayoutPanel.ResumeLayout(false); // 确保在异常情况下也恢复布局
                Console.WriteLine($"[UcCenterView] 统计更新错误: {ex.Message}");
            }
        }

        // 优化后的更新方法 - 直接更新而不重新查找控件
        public void UpdateChannelData(int channelIndex, string alphaValue, string betaValue, string deductPoints = "0")
        {
            if (channelIndex < 0 || channelIndex >= channelCount) return;

            try
            {
                this.BeginInvoke(new Action(() =>
                {
                    var alphaLabel = tableLayoutPanel.GetControlFromPosition(channelIndex + 1, 1) as UILabel;
                    if (alphaLabel != null && alphaLabel.Text != alphaValue)
                    {
                        alphaLabel.Text = alphaValue;
                        alphaLabel.Invalidate(); // === 只重绘这个控件 ===
                    }

                    var betaLabel = tableLayoutPanel.GetControlFromPosition(channelIndex + 1, 2) as UILabel;
                    if (betaLabel != null && betaLabel.Text != betaValue)
                    {
                        betaLabel.Text = betaValue;
                        betaLabel.Invalidate(); // === 只重绘这个控件 ===
                    }

                    var deductLabel = tableLayoutPanel.GetControlFromPosition(channelIndex + 1, 3) as UILabel;
                    if (deductLabel != null && deductLabel.Text != deductPoints)
                    {
                        deductLabel.Text = deductPoints;
                        deductLabel.Invalidate(); // === 只重绘这个控件 ===
                    }
                }));
            }
            catch (Exception ex)
            {
                Console.WriteLine($"[UcCenterView] 更新通道数据失败: {ex.Message}");
            }
        }
        // 新增：格式化计数显示
        private string FormatCount(long count)
        {
            if (count >= 1000000)
                return (count / 1000000.0).ToString("F1") + "M";
            else if (count >= 1000)
                return (count / 1000.0).ToString("F1") + "K";
            else
                return count.ToString();
        }

        // 新增：刷新阈值配置
        public void RefreshThresholds()
        {
            try
            {
                channelDataList = ChannelDataManager.LoadAllChannelData();
                channelThresholds.Clear();

                for (int i = 0; i < channelDataList.Count && i < channelCount; i++)
                {
                    channelThresholds[i] = channelDataList[i].Thresholds;
                }

                Console.WriteLine("[UcCenterView] 阈值配置已刷新");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"[UcCenterView] 刷新阈值配置失败: {ex.Message}");
            }
        }

        // 新增：初始化表头同步
        private void InitHeaderSync()
        {
            headerSyncTimer = new Timer { Interval = 1000 }; // 每秒检查一次
            headerSyncTimer.Tick += HeaderSyncTimer_Tick;
            headerSyncTimer.Start();
        }

        // 新增：表头同步定时器事件
        private void HeaderSyncTimer_Tick(object sender, EventArgs e)
        {
            if (plotPanel == null) return;

            // 如果PlotPanel处于手动模式，不更新表头
            if (plotPanel.IsManualMode) return;

            // 获取PlotPanel当前显示的通道
            int plotCurrentChannel = GetCurrentActiveChannel();

            // 如果通道发生变化，同步更新表头
            if (plotCurrentChannel != currentSelectedChannel && plotCurrentChannel >= 0)
            {
                UpdateHeaderSelection(plotCurrentChannel, false); // false表示不触发PlotPanel更新
            }
        }

        // 新增：获取当前活跃的通道（从PlotPanel中检测哪个通道正在显示）
        private int GetCurrentActiveChannel()
        {
            // 由于PlotViewPanel没有直接暴露当前通道索引，
            // 我们需要通过标题来判断当前通道
            if (plotPanel?.plotModel?.Title != null)
            {
                string title = plotPanel.plotModel.Title;
                if (title.Contains("通道"))
                {
                    // 提取通道号：从"通道 X - 电压分布"中提取X
                    try
                    {
                        int startIndex = title.IndexOf("通道") + 2;
                        int endIndex = title.IndexOf(" -");
                        if (startIndex > 1 && endIndex > startIndex)
                        {
                            string channelStr = title.Substring(startIndex, endIndex - startIndex).Trim();
                            if (int.TryParse(channelStr, out int channelNum))
                            {
                                return channelNum - 1; // 转换为0基索引
                            }
                        }
                    }
                    catch
                    {
                        // 解析失败，返回-1
                    }
                }
            }
            return -1;
        }

        // 修改：更新表头选中状态，增加是否同步PlotPanel的参数
        private void UpdateHeaderSelection(int channelIndex, bool syncToPlot = true)
        {
            // 先取消之前的选中状态
            if (currentSelectedChannel >= 0)
            {
                ResetHeaderStyle(currentSelectedChannel);
            }

            // 设置新的选中状态
            if (channelIndex >= 0 && channelIndex < channelHeaders.Length)
            {
                SetHeaderActiveStyle(channelIndex);
                currentSelectedChannel = channelIndex;

                // 根据参数决定是否同步到PlotPanel
                if (syncToPlot && plotPanel != null)
                {
                    plotPanel.ShowOnlyChannel(channelIndex);
                }
            }
            else
            {
                currentSelectedChannel = -1;
                if (syncToPlot && plotPanel != null)
                {
                    plotPanel.HideAllChannels();
                }
            }
        }

        // 新增：重置表头样式为默认状态
        private void ResetHeaderStyle(int channelIndex)
        {
            if (channelIndex >= 0 && channelIndex < channelHeaders.Length)
            {
                var headerButton = channelHeaders[channelIndex];
                headerButton.FillColor = Color.FromArgb(243, 249, 255);
                headerButton.ForeColor = Color.FromArgb(64, 158, 255);
                headerButton.RectColor = Color.FromArgb(216, 234, 255);
                headerButton.Font = new Font(headerButton.Font, FontStyle.Regular);
            }
        }

        // 新增：设置表头为激活样式
        // 修改 SetHeaderActiveStyle 方法
        private void SetHeaderActiveStyle(int channelIndex)
        {
            if (channelIndex >= 0 && channelIndex < channelHeaders.Length)
            {
                // 使用统一的通道颜色
                Color channelColor = AppConfig.ChannelColors[channelIndex % AppConfig.ChannelColors.Length];

                var headerButton = channelHeaders[channelIndex];
                headerButton.FillColor = channelColor;
                headerButton.ForeColor = Color.White;
                headerButton.RectColor = channelColor;
                headerButton.Font = new Font(headerButton.Font, FontStyle.Bold);
            }
        }

        private void BuildTableLayout()
        {
            tableLayoutPanel.SuspendLayout();


            tableLayoutPanel.Controls.Clear();
            tableLayoutPanel.ColumnStyles.Clear();
            tableLayoutPanel.RowStyles.Clear();

            tableLayoutPanel.ColumnCount = channelCount + 1;
            tableLayoutPanel.RowCount = 5; // 增加到5行：表头行、α通道行、β通道行、扣除点数行、结果查看行
                                           // === 添加这一行，设置单元格边框 ===
            tableLayoutPanel.CellBorderStyle = TableLayoutPanelCellBorderStyle.Single;
            // 设置列样式
            for (int i = 0; i < tableLayoutPanel.ColumnCount; i++)
                tableLayoutPanel.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 100f / tableLayoutPanel.ColumnCount));

            // 设置行样式
            for (int i = 0; i < tableLayoutPanel.RowCount; i++)
                tableLayoutPanel.RowStyles.Add(new RowStyle(SizeType.AutoSize));

            // 使用统一的通道颜色定义
            Color[] channelColors = AppConfig.ChannelColors;

            // === 第一行：表头行 ===
            // 表头第一列
            var firstHeaderLabel = new UILabel
            {
                Text = "",
                TextAlign = ContentAlignment.MiddleCenter,
                Dock = DockStyle.Fill,
                BackColor = Color.FromArgb(243, 249, 255),
                ForeColor = Color.FromArgb(64, 158, 255),
                Font = new Font("微软雅黑", 10F, FontStyle.Bold)
            };
            tableLayoutPanel.Controls.Add(firstHeaderLabel, 0, 0);

            // 初始化通道表头数组
            channelHeaders = new UIButton[channelCount];

            // 可点击的通道表头
            for (int i = 1; i <= channelCount; i++)
            {
                var headerButton = new UIButton
                {
                    Text = $"通道{i}",
                    Dock = DockStyle.Fill,
                    Font = new Font("微软雅黑", 10F, FontStyle.Bold),
                    Tag = i - 1,
                    Name = $"headerChannel{i}",
                    FillColor = Color.FromArgb(243, 249, 255),
                    ForeColor = Color.FromArgb(64, 158, 255),
                    RectColor = Color.FromArgb(216, 234, 255),
                    RectSize = 2,
                    RadiusSides = UICornerRadiusSides.All,
                    Radius = 6,
                    Cursor = Cursors.Hand
                };

                headerButton.Click += ChannelHeader_Click;
                channelHeaders[i - 1] = headerButton;
                tableLayoutPanel.Controls.Add(headerButton, i, 0);
            }

            // === 第二行：α通道行 ===
            var alphaLabel = new UILabel
            {
                Text = "α通道",
                TextAlign = ContentAlignment.MiddleCenter,
                Dock = DockStyle.Fill,
                BackColor = Color.FromArgb(250, 250, 250),
                ForeColor = Color.FromArgb(102, 102, 102),
                Font = new Font("微软雅黑", 9F)
            };
            tableLayoutPanel.Controls.Add(alphaLabel, 0, 1);

            for (int i = 0; i < channelCount; i++)
            {
                var alphaValueLabel = new UILabel
                {
                    Text = "0",
                    TextAlign = ContentAlignment.MiddleCenter,
                    Dock = DockStyle.Fill,
                    BackColor = Color.White,
                    ForeColor = Color.FromArgb(102, 102, 102),
                    Font = new Font("微软雅黑", 9F),
                    Name = $"alphaValue{i}"
                };
                tableLayoutPanel.Controls.Add(alphaValueLabel, i + 1, 1);
            }

            // === 第三行：β通道行 ===
            var betaLabel = new UILabel
            {
                Text = "β通道",
                TextAlign = ContentAlignment.MiddleCenter,
                Dock = DockStyle.Fill,
                BackColor = Color.FromArgb(250, 250, 250),
                ForeColor = Color.FromArgb(102, 102, 102),
                Font = new Font("微软雅黑", 9F)
            };
            tableLayoutPanel.Controls.Add(betaLabel, 0, 2);

            for (int i = 0; i < channelCount; i++)
            {
                var betaValueLabel = new UILabel
                {
                    Text = "0",
                    TextAlign = ContentAlignment.MiddleCenter,
                    Dock = DockStyle.Fill,
                    BackColor = Color.White,
                    ForeColor = Color.FromArgb(102, 102, 102),
                    Font = new Font("微软雅黑", 9F),
                    Name = $"betaValue{i}"
                };
                tableLayoutPanel.Controls.Add(betaValueLabel, i + 1, 2);
            }

            // === 第四行：扣除点数行 (新增) ===
            var deductPointsLabel = new UILabel
            {
                Text = "扣除点数",
                TextAlign = ContentAlignment.MiddleCenter,
                Dock = DockStyle.Fill,
                BackColor = Color.FromArgb(250, 250, 250),
                ForeColor = Color.FromArgb(102, 102, 102),
                Font = new Font("微软雅黑", 9F)
            };
            tableLayoutPanel.Controls.Add(deductPointsLabel, 0, 3);

            for (int i = 0; i < channelCount; i++)
            {
                var deductPointsValueLabel = new UILabel
                {
                    Text = "0",
                    TextAlign = ContentAlignment.MiddleCenter,
                    Dock = DockStyle.Fill,
                    BackColor = Color.White,
                    ForeColor = Color.FromArgb(102, 102, 102),
                    Font = new Font("微软雅黑", 9F),
                    Name = $"deductPoints{i}"
                };
                tableLayoutPanel.Controls.Add(deductPointsValueLabel, i + 1, 3);
            }

            // === 第五行：结果查看行 (原第四行) ===
            var resultLabel = new UILabel
            {
                Text = "结果查看",
                TextAlign = ContentAlignment.MiddleCenter,
                Dock = DockStyle.Fill,
                BackColor = Color.FromArgb(250, 250, 250),
                ForeColor = Color.FromArgb(102, 102, 102),
                Font = new Font("微软雅黑", 9F, FontStyle.Bold)
            };
            tableLayoutPanel.Controls.Add(resultLabel, 0, 4); // 行索引改为4

            // 为每个通道创建查看按钮
            for (int i = 0; i < channelCount; i++)
            {
                var resultButton = new UIButton
                {
                    Text = "查看",
                    Dock = DockStyle.Fill,
                    Font = new Font("微软雅黑", 10F, FontStyle.Bold),
                    Tag = i,
                    Name = $"resultButton{i}",
                    FillColor = Color.FromArgb(243, 249, 255),
                    ForeColor = Color.FromArgb(64, 158, 255),
                    RectColor = Color.FromArgb(216, 234, 255),
                    RectSize = 2,
                    RadiusSides = UICornerRadiusSides.All,
                    Radius = 6,
                    Cursor = Cursors.Hand
                };
                resultButton.Click += ResultButton_Click;
                tableLayoutPanel.Controls.Add(resultButton, i + 1, 4); // 行索引改为4
            }

            tableLayoutPanel.ResumeLayout();
        }

        // 结果查看按钮点击事件
        private void ResultButton_Click(object sender, EventArgs e)
        {
            var button = sender as UIButton;
            if (button == null) return;

            int channelIndex = (int)button.Tag;

            try
            {
                // === 从JSON配置加载完整通道数据 ===
                var channelData = ChannelDataManager.LoadChannelData(channelIndex);

                // === 收集展示用的通道信息 ===
                var displayData = new ChannelDisplayData
                {
                    ChannelIndex = channelIndex,
                    ChannelName = $"通道{channelIndex + 1}",

                    // 基本配置信息
                    ThresholdConfig = channelData.Thresholds,
                    WorkConditions = channelData.WorkConditions,
                    StepLength = channelData.StepLength,
                    LastModified = channelData.LastModified,

                    // 实时统计数据
                    RealtimeStats = channelData.RealtimeStatistics,

                    // 各种测量结果
                    BackgroundResult = channelData.MeasurementResults?.BackgroundMeasurement,
                    WorkingSourceResult = channelData.MeasurementResults?.WorkingSourceMeasurement,
                    StandardSourceResult = channelData.MeasurementResults?.StandardSourceMeasurement,
                    GeneralSampleResult = channelData.MeasurementResults?.GeneralSampleResult,
                    WaterSampleResult = channelData.MeasurementResults?.WaterSampleResult,
                    BioSampleResult = channelData.MeasurementResults?.BioSampleResult,
                    GasSampleResult = channelData.MeasurementResults?.GasSampleResult,
                    EnvSampleResult = channelData.MeasurementResults?.EnvSampleResult,

                    // 当前界面显示值
                    //CurrentAlphaValue = GetDisplayValue(channelIndex, 1),
                    //CurrentBetaValue = GetDisplayValue(channelIndex, 2),
                    //CurrentDeductValue = GetDisplayValue(channelIndex, 3),

                    //// 设备状态
                    //DeviceStatus = GetChannelDeviceStatus(channelIndex)
                };

                // 打开增强版结果查看窗口
                var resultForm = new ChannelResultViewForm(displayData);
                resultForm.ShowDialog(this);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"[UcCenterView] 打开通道{channelIndex + 1}结果窗口失败: {ex.Message}");
                MessageBox.Show($"打开通道结果窗口失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        // === 添加展示数据结构类 ===
        public class ChannelDisplayData
        {
            public int ChannelIndex { get; set; }
            public string ChannelName { get; set; }

            // 基本配置
            public ThresholdData ThresholdConfig { get; set; }
            public WorkConditionData WorkConditions { get; set; }
            public double StepLength { get; set; }
            public DateTime LastModified { get; set; }

            // 统计数据
            public RealtimeStatisticsData RealtimeStats { get; set; }

            // 各种测量结果
            public Model.BackgroundMeasurementResult BackgroundResult { get; set; }
            public WorkingSourceMeasurementResult WorkingSourceResult { get; set; }
            public StandardSourceMeasurementResult StandardSourceResult { get; set; }
            public GeneralSampleMeasurementResult GeneralSampleResult { get; set; }
            public WaterSampleMeasurementResult WaterSampleResult { get; set; }
            public BioSampleMeasurementResult BioSampleResult { get; set; }
            public GasSampleMeasurementResult GasSampleResult { get; set; }
            public EnvSampleMeasurementResult EnvSampleResult { get; set; }

            // 当前显示值
            public string CurrentAlphaValue { get; set; }
            public string CurrentBetaValue { get; set; }
            public string CurrentDeductValue { get; set; }
            public string DeviceStatus { get; set; }
        }

        // 修改：表头点击事件
        private void ChannelHeader_Click(object sender, EventArgs e)
        {
            var headerButton = sender as UIButton;
            if (headerButton == null) return;

            int channelIndex = (int)headerButton.Tag;

            if (currentSelectedChannel == channelIndex)
            {
                // 取消选中
                UpdateHeaderSelection(-1, true);
            }
            else
            {
                // 选中新通道
                UpdateHeaderSelection(channelIndex, true);
            }
        }

        // 保留但简化原有方法
        private void SelectChannel(int channelIndex)
        {
            UpdateHeaderSelection(channelIndex, true);
        }

        private void DeselectCurrentChannel()
        {
            UpdateHeaderSelection(-1, true);
        }

        private void InitPlotPanel()
        {
            if (plotPanel != null)
            {
                if (outerLayout.Controls.Contains(plotPanel))
                    outerLayout.Controls.Remove(plotPanel);
            }

            plotPanel = new PlotViewPanel();
            plotPanel.Dock = DockStyle.Fill;
            outerLayout.Controls.Add(plotPanel, 0, 1);

            // 模拟空数据让它画空轮廓
            //for (int ch = 0; ch < AppConfig.ChannelCount; ch++)
            //{
            //    for (double v = 0; v <= 3.0; v += 0.005)
            //    {
            //        plotPanel.AddVoltagePoint(ch, v);
            //    }
            //}
            plotPanel.UpdateHistogram();
        }

        // 修改：增强版startPlotPanel方法，集成统计功能
        public void startPlotPanel(UltraHighPerformanceChannelParser parser)
        {
            try
            {
                Console.WriteLine("[UcCenterView] 启动增强版Plot面板，集成统计功能");

                // 启动绘图面板的通道切换功能
                this.plotPanel.StartChannelSwitching();

                // 创建带统计功能的数据适配器，传入this作为centerView参数
                dataAdapter = new HighPerformanceDataAdapter(plotPanel, parser, this);

                // 启动数据适配器
                dataAdapter.Start();

                // 启动统计数据更新定时器
                statisticsUpdateTimer.Start();

                // 开始新的统计会话
                ChannelDataManager.StartStatisticsSession($"Session_{DateTime.Now:yyyyMMdd_HHmmss}");

                Console.WriteLine("[UcCenterView] 增强版Plot面板已启动，统计功能已激活");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"[UcCenterView] 启动增强版Plot面板失败: {ex.Message}");
                MessageBox.Show($"启动Plot面板失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        public void ConnectToParser(UltraHighPerformanceChannelParser parser)
        {
            plotPanel.ConnectToParser(parser);
        }

        // 公开方法...
        public void ShowChannelByIndex(int channelIndex)
        {
            if (channelIndex >= 0 && channelIndex < channelHeaders.Length)
            {
                UpdateHeaderSelection(channelIndex, true);
            }
        }

        public void ClearSelection()
        {
            UpdateHeaderSelection(-1, true);
        }

        public int GetSelectedChannel()
        {
            return currentSelectedChannel;
        }


        // 新增方法：更新扣除点数
        public void UpdateDeductPoints(int channelIndex, string deductValue)
        {
            if (channelIndex < 0 || channelIndex >= channelCount) return;

            var deductLabel = tableLayoutPanel.GetControlFromPosition(channelIndex + 1, 3) as UILabel;
            if (deductLabel != null)
            {
                deductLabel.Text = deductValue;
            }
        }

        // 新增方法：获取扣除点数值
        public string GetDeductPoints(int channelIndex)
        {
            if (channelIndex < 0 || channelIndex >= channelCount) return "0";

            var deductLabel = tableLayoutPanel.GetControlFromPosition(channelIndex + 1, 3) as UILabel;
            return deductLabel?.Text ?? "0";
        }

        // 新增：停止增强版Plot面板
        public void StopPlotPanel()
        {
            try
            {
                Console.WriteLine("[UcCenterView] 停止增强版Plot面板");

                // 停止统计数据更新定时器
                statisticsUpdateTimer?.Stop();

                // 停止数据适配器
                dataAdapter?.Stop();

                // 停止绘图面板
                this.plotPanel?.StopChannelSwitching();

                // 结束当前统计会话
                ChannelDataManager.EndStatisticsSession($"Session_{DateTime.Now:yyyyMMdd_HHmmss}");

                Console.WriteLine("[UcCenterView] 增强版Plot面板已停止，统计数据已保存");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"[UcCenterView] 停止增强版Plot面板失败: {ex.Message}");
            }
        }



        // 新增：获取通道阈值配置（供统计计算使用）
        public ThresholdData GetChannelThresholds(int channelIndex)
        {
            if (channelThresholds.ContainsKey(channelIndex))
            {
                return channelThresholds[channelIndex];
            }

            // 如果缓存中没有，从数据管理器加载
            var channelData = ChannelDataManager.LoadChannelData(channelIndex);
            return channelData.Thresholds;
        }

        // 新增：重置所有统计数据
        public void ResetAllStatistics()
        {
            try
            {
                ChannelDataManager.ResetAllChannelStatistics();

                // 清空界面显示
                for (int i = 0; i < channelCount; i++)
                {
                    UpdateChannelData(i, "0", "0", "0");
                }

                Console.WriteLine("[UcCenterView] 所有统计数据已重置");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"[UcCenterView] 重置统计数据失败: {ex.Message}");
            }
        }

    

        // 资源释放
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                headerSyncTimer?.Dispose();
                statisticsUpdateTimer?.Dispose();
                dataAdapter?.Dispose();
                if (components != null)
                    components.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}